package com.boarsoft.demo.order;

import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.boarsoft.boar.demo.order.entity.PocOrder;
import com.boarsoft.boar.demo.order.service.PocOrderService;
import com.boarsoft.rpc.core.RpcCore;

public class OrderPlaceClient extends AbstractJavaSamplerClient {
	private static final Logger log = LoggerFactory.getLogger(OrderPlaceClient.class);

	public static volatile ClassPathXmlApplicationContext ctx;
	public static volatile PocOrderService orderService;

	@Override
	public SampleResult runTest(JavaSamplerContext jsc) {
		SampleResult sr = new SampleResult();
		// try {
		sr.sampleStart();
		int tenantId = 12344, userId = 666666, productId = 4, productNum = 1, amount = 1;
		PocOrder o = new PocOrder();
		if (jsc != null) {
			o.setTenantId(jsc.getIntParameter("tenantId", tenantId));
			o.setUserId(jsc.getIntParameter("userId", userId));
			o.setProductId(jsc.getIntParameter("productId", productId));
			o.setProductNum(jsc.getIntParameter("productNum", productNum));
			o.setAmount(jsc.getIntParameter("amount", amount));
			orderService.place(o);
		}
		boolean ok = orderService.place(o);
		sr.setResponseData(String.valueOf(ok), "UTF-8");
		sr.setDataType(SampleResult.TEXT);
		sr.setSuccessful(ok);
		sr.sampleEnd();
		// } catch (Exception e) {
		// log.error("Error on run test", e);
		// }
		return sr;
	}

	@Override
	public void setupTest(JavaSamplerContext jsc) {
		synchronized (OrderPlaceClient.class) {
			if (ctx == null) {
				ctx = new ClassPathXmlApplicationContext("classpath:conf/context.xml");
				orderService = ctx.getBean(PocOrderService.class);
			}
		}
	}

	@Override
	public void teardownTest(JavaSamplerContext context) {
		log.info("RpcCore is shutting down");
		try {
			RpcCore.getCurrentInstance().shutdown();
		} catch (Exception e) {
			log.error("Error on close application context", e);
		} finally {
			ctx.close();
		}
	}

	public static void main(String[] args) {
		OrderPlaceClient osc = new OrderPlaceClient();
		osc.setupTest(null);
		osc.runTest(null);
	}
}
